<template>
  <a-row :gutter="24">
    <a-col :md="4" :sm="24">
      <a-card :bordered="false" :loading="treeLoading">
        <a-directory-tree
          v-if="treeList.length"
          :showIcon="false"
          :treeData="treeList"
          @select="handleClick"
          :defaultExpandAll="true"
          :replaceFields="replaceFields"
          style="overflow: unset"
        />
      </a-card>
    </a-col>

    <a-col :md="19" :sm="24">
      <a-card :bordered="false">
        <div class="table-page-search-wrapper">
          <a-form layout="inline">
            <a-row :gutter="48">

              <a-col :md="6" :sm="24">
                <a-form-item label="网关名称">
                  <a-select
                    style="width: 100%"
                    v-model="queryParam.gatewayId"
                    allow-clear
                    placeholder="请选择网关名称">
                    <a-select-option v-for="(item,ind) in gatewayList" :key="ind" :value="item.id">{{ item.gatewayName
                    }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>

              <a-col :md="(!advanced && 8) || 24" :sm="24">
                <span
                  class="table-page-search-submitButtons"
                  style="padding-left: 16px;"
                  :style="(advanced && { float: 'right', overflow: 'hidden' }) || {}"
                >
                  <a-button
                    type="primary"
                    class="btn_search_reset"
                    @click="$refs.table.refresh(true)"
                  ><a-icon type="search"/>查询</a-button>
                </span>
              </a-col>
              <a-col :md="10" :sm="24">
                <span
                  class="table-page-search-submitButtons"
                  style="float: right;"
                >
                  <a-button
                    class="btn_add"
                    type="primary"
                    @click="handleAdd"
                    icon="plus"
                  >新增</a-button>
                </span>
              </a-col>
            </a-row>
          </a-form>
        </div>

        <s-table
          ref="table"
          size="default"
          :columns="columns"
          :data="loadData"
          :alert="true"
          :rowKey="(record) => record.id"
        >
          <span slot="taskType" slot-scope="text">
            {{ taskTypeFilter(text) }}
          </span>

          <span slot="taskStatus" slot-scope="text">
            {{ taskStatusFilter(text) }}
          </span>

          <span slot="action" slot-scope="text, record">
            <template v-if="record.taskStatus==='0'">
              <a-popconfirm placement="topRight" title="确认下发这个任务？？" @confirm="() => issued(record.id)">
                <a class="btn_edit">下发</a>
              </a-popconfirm>
            </template>
            <template v-if="record.taskType!=='1' && record.taskType!=='3' && record.taskType!=='4'">
              <a-divider type="vertical"/>
              <a-popconfirm placement="topRight" title="确认删除？" @confirm="() => del(record)">
                <a class="btn_del">删除</a>
              </a-popconfirm>
            </template>
            <template v-if="record.taskStatus==='1'&& ( record.taskType==='1' || record.taskType==='3' || record.taskType==='4' )">
              <a-popconfirm placement="topRight" title="确认撤销这个任务？？" @confirm="() => rollback(record.id)">
                <a class="btn_edit">撤销</a>
              </a-popconfirm>
            </template>
          </span>
        </s-table>
        <add-form ref="addForm" @ok="handleOk"/>
        <edit-form ref="editForm" @ok="handleOk"/>
      </a-card>
    </a-col>
  </a-row>
</template>

<script>
  import { STable } from '@/components'
  import { page, del, rollback, issued } from '@/api/modular/main/gatewaytask/gatewaytask'
  import addForm from './addForm'
  import editForm from './editForm'
  import { Empty } from 'ant-design-vue'
  import { treeList } from '@/api/modular/main/bizstation/bizStationManage'
  import moment from 'moment'
  import { gatewayList } from '@/api/modular/main/bizgateway/bizGatewayManage'
  import { sysDictTypeDropDown } from '@/api/modular/system/dictManage'

  export default {
    components: {
      STable,
      addForm,
      editForm
    },

    data () {
      return {
        advanced: false, // 高级搜索 展开/关闭
        gatewayList: [],
        gatewayTaskStatusList: [],
        gatewayTaskTypeList: [],
        queryParam: {
          stationId: 0
        }, // 查询参数
        columns: [
          {
            title: '任务类型',
            dataIndex: 'taskType',
            scopedSlots: { customRender: 'taskType' }
          },
          {
            title: '任务状态',
            dataIndex: 'taskStatus',
            scopedSlots: { customRender: 'taskStatus' }
          },
          {
            title: '创建日期',
            dataIndex: 'createTime',
            width: 150,
            align: 'center'
          },
          {
            title: '下发日期',
            dataIndex: 'issuedTime',
            width: 150,
            align: 'center'
          },
          {
            title: '操作',
            dataIndex: 'action',
            scopedSlots: { customRender: 'action' },
            width: 250,
            align: 'center'
          }
        ],
        // 加载数据方法 必须为 Promise 对象
        loadData: (parameter) => {
          return page(Object.assign(parameter, this.queryParam)).then((res) => {
            return res.data
          })
        },
        treeList: [],
        gatewayLoading: true,
        simpleImage: Empty.PRESENTED_IMAGE_SIMPLE,
        selectedRowKeys: [],
        selectedRows: [],
        defaultExpandedKeys: [],
        replaceFields: {
          key: 'id'
        },
        treeLoading: true,
        stationId: '',
        btnLoading: false
      }
    },

    created () {
      this.getStationTree()
      this.getGatewayTaskStatusList()
      this.getGatewayTaskTypeList()
    },

    methods: {
      handleAdd () {
        if (this.stationId === '') {
          this.$message.warn('请选择站点')
          return
        }
        this.$refs.addForm.add(this.stationId)
      },
      taskTypeFilter (record) {
        console.log(record)
        let str = ''
        this.gatewayTaskTypeList.forEach(item => {
          if (record === item.code) {
            str = item.value
          }
        })
        return str
      },
      taskStatusFilter (record) {
        let str = ''
        this.gatewayTaskStatusList.forEach(item => {
          if (record === item.code) {
            str = item.value
          }
        })
        return str
      },
      getGatewayTaskStatusList () {
        sysDictTypeDropDown({ code: 'gateway_task_status' }).then((res) => {
          if (res.success) {
            this.gatewayTaskStatusList = res.data
          }
        })
      },
      getGatewayTaskTypeList () {
        sysDictTypeDropDown({ code: 'gateway_task_type' }).then((res) => {
          if (res.success) {
            this.gatewayTaskTypeList = res.data
          }
        })
      },
      getGatewayList (stationId) {
        gatewayList({ stationId: stationId }).then(res => {
          if (res.success) {
            this.gatewayList = res.data
            this.gatewayIds = []
            this.gatewayList.filter(value => {
              this.gatewayIds.push(value.id)
            })
            this.queryParam.gatewayIds = this.gatewayIds.toString()
            this.handleOk()
          }
        })
      },
      del (record) {
        record.createdAt = moment(record.createdAt).format('YYYY-MM-DD HH:mm:ss')
        del(record)
          .then((res) => {
            if (res.success) {
              this.$message.success('删除成功')
              this.$refs.table.refresh()
            } else {
              this.$message.error('删除失败：' + res.message)
            }
          })
          .catch((err) => {
            this.$message.error('删除错误：' + err.message)
          })
      },
      issued (id) {
        const param = { id: id }
        issued(param)
          .then((res) => {
            if (res.success) {
              this.$message.success('下发成功')
              this.$refs.table.refresh()
            } else {
              this.$message.error('下发失败：' + res.message)
            }
          })
          .catch((err) => {
            this.$message.error('下发错误：' + err.message)
          })
      },
      rollback (id) {
        const param = { id: id }
        rollback(param)
          .then((res) => {
            if (res.success) {
              this.$message.success('撤销成功')
              this.$refs.table.refresh()
            } else {
              this.$message.error('撤销失败：' + res.message)
            }
          })
          .catch((err) => {
            this.$message.error('撤销错误：' + err.message)
          })
      },
      getStationTree () {
        treeList(Object.assign(this.queryParam)).then((res) => {
          this.treeLoading = false
          if (!res.success) {
            return
          }
          this.treeList = res.data
        })
      },
      toggleAdvanced () {
        this.advanced = !this.advanced
      },
      handleOk () {
        this.$refs.table.refresh()
      },
      onSelectChange (selectedRowKeys, selectedRows) {
        this.selectedRowKeys = selectedRowKeys
        this.selectedRows = selectedRows
      },
      handleClick (e) {
        if (e.length > 0) {
          this.queryParam = {}
          this.stationId = e.toString()
          this.getGatewayList(e.toString())
        } else {
          this.queryParam.gatewayIds = ''
          this.handleOk()
        }
      },
      isShow () {
        return !!this.stationId
      }
    }
  }
</script>
<style lang="less" scoped>
  /*@import '../~@/assets/css/list.less';*/
  .table-operator {
    margin-bottom: 18px;
  }

  button {
    margin-right: 8px;
  }

  .ant-tree li {
    overflow: no-content !important;
    white-space: pre-wrap !important;
  }
  .table-page-search-wrapper{
    padding: 0 10px;
    /deep/ .ant-row{
      margin-left: 0px !important;
    }
  }
</style>
